"""应用主程序文件"""
import traceback

from fastapi import FastAPI, Request
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse

from .core import setting

from soulapi import routers

# 实例化应用
soulapi = FastAPI(
    title='Soul House System API Docs',  # 应用标题
    version='1.2.3',  # 版本
    description='心灵小屋系统API接口服务',  # 描述
    docs_url='/docs',  # 自定义文件地址
    redoc_url='/redoc',
)

# 设置跨域,中间件
soulapi.add_middleware(
    CORSMiddleware,
    allow_origins=setting.ORIGINS,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 全局的异常捕获
@soulapi.exception_handler(Exception)
async def unicorn_exception_handler(request: Request, exc: Exception):
    s = traceback.format_exc()
    s_list = s.split("\n")
    s_list.pop()
    stack_list = []
    for s in s_list:
        stack_list.append(s.lstrip())
    if len(stack_list) > 6:
        stack_res = stack_list[-6:]
    else:
        stack_res = stack_list.pop()

    return JSONResponse(
        status_code=500,
        content={
            "code": 65535,
            "message": "服务器异常",
            "detail": stack_res,
        },
    )


# APIRouter注册到核心对象，include_router()注册函数，prefix添加路由路径，tags标签，路由分组，
# soulapi.include_router(routers.router_admin, prefix='/admin', tags=['管理员'])

soulapi.include_router(routers.router_newstype, prefix='/newstype', tags=['文章分类'])
